from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from .serializer import *
from rest_framework import status
from django.db.models import Q
from django.core.paginator import Paginator

# 分类
class CategoryView(APIView):
    def get(self,request):
        # 获取所有的分类数据
        catequeryset=models.Cagegory.objects.all()
        # 序列化
        obj=CategorySerializer(catequeryset,many=True)
        # 返回
        return Response(obj.data)


# 商品
class GoodsView(APIView):
    # 读取数据
    def get(self,request):
        # 1 接收参数
        p=request.GET.get('p',1)
        keyword=request.GET.get('keyword','').strip()
        cate=int(request.GET.get('cate',0))

        # 查询数据
        if cate:
            goodquerset=models.Goods.objects.filter(cate=cate).filter(Q(title__contains=keyword)|Q(cate__name__contains=keyword)).all()
        else:
            goodquerset = models.Goods.objects.filter(Q(title__contains=keyword)|Q(cate__name__contains=keyword)).all()

        # 3 分页
        page_obj=Paginator(goodquerset,per_page=4)

        # 获取分页的范围
        page=[i for i in page_obj.page_range]

        # 获取当前页的数据
        try:
            page_data=page_obj.page(p)
        except:
            page_data = page_obj.page(1)

        # 获取上一页和下一页
        previous=page_data.has_previous()
        next=page_data.has_next()

        # 序列化当前数据
        obj=GoodsSerializer(page_data,many=True)

        # 构造数据
        data={
            'data':obj.data,
            'page':page,
            'previous':previous,
            'next':next
        }

        # 返回
        return Response(data)





    # 添加商品
    def post(self,request):
        # 1 接收参数
        title=request.POST.get('title','').strip()
        price = request.POST.get('price', '0')
        img = request.FILES.get('img')
        cate = request.POST.get('cate', '0')

        # 验证数据的重复性
        goodobj=models.Goods.objects.filter(title=title).first()
        if goodobj:
            return Response('数据已存在',status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        data={
            'title':title,
            'price':price,
            'img':img,
            'cate':cate
        }

        # 反序列化
        obj=GoodsSerializer(data=data)

        if obj.is_valid():
            obj.save()
            return Response('添加成功')

        print(obj.errors)
        return Response('参数有误',status=status.HTTP_500_INTERNAL_SERVER_ERROR)

